<!--
	作者：1048107945@qq.com
	时间：2020-02-29
	描述：这是工资制作主页面
-->
<template>
  <div class="app-container clearfix">
    <!-- 列表 -->
    <salarymake-table
      :id="id"
      :data="listData"
      :search-params="searchKey"
      :total-count="totalCount"
      :list-loading="listLoading"
      :type="type"
      :dept-name="deptName"
      :params-data="paramsData"
      :pnum="pnum"
      :salary-date="searchKey.salaryDate | formatDate('yyyy-MM')"
      @on-import="handleImport"
      @on-reelect="handleReelect"
      @on-redo="handleRedo"
      @on-save="handleSave"
      @on-approve="handleApprove"
      @on-export="handleExport"
      @on-init="handleInitList"
      @on-edit="handleEditShow"
      @on-delete="handleDelete"
    />
    <!-- 选择部门和月份弹出框 -->
    <salarymake-select
      :visible.sync="isShowSelectParams"
      :department-all-list-data="departmentAllListData"
    />
  </div>
</template>

<script>
import {
  getEmployeeListCreateAPI,
  getEmployeeListUpdateAPI,
  saveSalarymakeAPI,
  redoSalarymakeAPI,
  submitApproveAPI,
  exportListAPI3
} from '@/api/todo/salarymake'
import { SalarymakeTable, SalarymakeSelect } from './components'
import { formatDate, formatTimestamp } from '@/utils/utils'
import commonMixins from '@/mixins/common'
import treeAllListData from '@/mixins/treeAllListData'
import salaryImportExcel from '@/mixins/salaryImportExcel3'
import filters from '@/filters/filters'

export default {
  name: 'StockSalarymakeList',
  components: {
    SalarymakeTable,
    SalarymakeSelect
  },
  mixins: [commonMixins, filters, treeAllListData, salaryImportExcel],
  props: {},
  data() {
    return {
      pnum: 0,
      paramsData: {},
      type: '1', // 1、新增 2、修改 3、查看
      id: '', // 月薪列表ID
      initParams: { // 初始化参数
        pageNum: 1, // 当前页数
        pageSize: 10, // 每页个数
        sort: '', // 排序
        deptId: null, // 部门ID
        salaryDate: '' // 发放月份
      },
      searchKey: {}, // 搜索参数
      editInfo: { // 编辑弹出框
        visible: false, // 是否显示模态框
        detailInfo: {}
      },
      totalCount: 0, // 分页用的列表总条数
      listLoading: false,
      isShowSelectParams: false, // 如果没有选择部门或者月份就显示弹出框
      deptName: '',
      importInstance: undefined,
      listData: [] // 列表数据
    }
  },
  computed: {},
  watch: {
    initParams: {
      handler: function(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
          this.searchKey = JSON.parse(JSON.stringify(newVal))
        }
      },
      deep: true,
      immediate: true
    },
    isShowSelectParams(newVal, oldVal) {
      const { id, type } = this
      const { deptId, salaryDate } = this.searchKey
      if (!newVal && (!deptId || !salaryDate)) {
        this.$nextTick(() => {
          // this.isShowSelectParams = true
          this.$notify.error({
            title: '错误',
            message: '必须要选择部门和发放月份!'
          })
        })
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    goBack() {
      this.$router.replace({
        name: 'Salary'
      })
    },
    goSalaryMake({ type, data }) { // 进入月薪制作
      let query = { type }
      if (type === '1') {
        query = {
          ...query,
          ...data
        }
      } else {
        query['id'] = data.id
        query['title'] = this.paramsData.title
      }
      this.$router.replace({
        name: 'stockSalarymake',
        query
      })
    },
    formatParams(listData) { // 格式化参数
      // alert(this.paramsData.title);

      const { id, type } = this
      const { deptId, salaryDate } = this.searchKey
      const params = {
        salaryMonth: salaryDate,
        deptId: deptId,
        title: this.paramsData.title,
        salaryType: this.paramsData.salaryType,
        hrSalaryMonths: []
      }
      listData.forEach((item, index) => {
        params.hrSalaryMonths[index] = {
          ...item,
          ...{
            salaryDate: salaryDate,
            deptId: deptId
          }
        }
      })
      if (type !== '1') { // 修改、查看
        params.id = id
      }
      // console.log(params)
      // console.log(JSON.stringify(params))
      return params
    },
    handleReelect() { // 重新选择部门和月份
      this.isShowSelectParams = true
    },
    handleEditShow(data = {}) { // 编辑－显示弹出框
      this.editInfo.visible = true
      this.editInfo.detailInfo = data
    },
    handleCreated() { // 添加成功
      this.searchKey.page = 1
      this.getListData()
    },
    handleUpdated() { // 编辑成功
      this.getListData()
    },
    handleInitList(params = {}) { // 初始化列表
      this.searchKey = {
        ...this.searchKey,
        ...params
      }
      this.getListData()
    },
    handleSave(listData) { // 保存
      const params = this.formatParams(listData)
      this.saveData(params)
    },
    handleRedo() { // 重做
      this.$confirm(`是否确定重做，重做后之前数据不可恢复！！！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.getRedoListData()
      }).catch(() => {
      })
    },
    handleApprove(listData) { // 是否审批
      this.$confirm(`是否提交进入审批流程?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = this.formatParams(listData)
        this.submitApproveData(params)
      }).catch(() => {
      })
    },

    // add by yyf
    async handleImport() {
      // salaryImportExcel()
      // console.log(response)
    },

    handleExport() { // 导出按钮操作
      const { id, type } = this
      if (type === '1' && !id) {
        this.$notify.error({
          title: '错误',
          message: '请先保存数据！'
        })
      } else {
        this.$confirm('是否确认导出所有数据?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            const response = await exportListAPI3({
              id
            })
            this.downloadFile(response)
          } catch (error) {
            // console.log(error)
            this.$notify.error({
              title: '错误',
              message: error.message || '操作失败！'
            })
          }
        }).catch(() => {
        })
      }
    },
    handleDelete(data = {}) { // 删除
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { listData } = this
        this.listData = listData.filter((item, index) => {
          return item.employeeId !== data.employeeId
        })

        this.pnum -= 1
        if (this.pnum < 0) {
          this.pnum = 0
        }
      }).catch(() => {
      })
    },
    async getRedoListData() { // 获取重做列表数据
      try {
        const { id } = this
        this.listLoading = true
        const response = await redoSalarymakeAPI({
          id: id,
          salaryType: 11
        })
        const result = response
        if (+result.code === 200) {
          const resultData = result.data.hrSalaryMonths || []
          this.listData = resultData.map((item) => {
            item.baseSalary = item.salaryBase
            item.assessmentSalary = item.salaryAssessment
            item.postSalary = item.salaryPost
            item.allowanceSalary = item.salaryAllowance
            return item
          })
          this.totalCount = result.data.hrSalaryMonths.length
          this.pnum = this.totalCount
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '获取列表失败!'
        })
      } finally {
        this.listLoading = false
      }
    },
    async submitApproveData(params) { // 审批－请求数据
      try {
        this.listLoading = true
        const response = await submitApproveAPI({
          ...params,
          ...{ pnum: this.pnum, salaryType: 11 }
        })
        const result = response
        if (+result.code === 200) {
          this.$store.dispatch('tagsView/delVisitedView', this.$route)
          this.goBack()
          this.$notify({
            title: '成功',
            message: result.msg || '审批提交成功！',
            type: 'success',
            duration: 4000
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '审批提交失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '审批提交失败！'
        })
      } finally {
        this.listLoading = false
      }
    },
    async saveData(params = {}) { // 保存－请求数据
      try {
        const { type } = this
        this.listLoading = true
        console.log(params)
        const response = await saveSalarymakeAPI({
          ...params,
          ...{
            pnum: this.pnum,
            salaryType: 11
          }
        })
        const result = response
        if (+result.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功！',
            type: 'success',
            duration: 2000
          })
          if (type === '1') {
            const id = result.data.id
            this.goSalaryMake({
              type: '2',
              data: { id }
            })
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '保存失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '保存失败！'
        })
      } finally {
        this.listLoading = false
      }
    },
    async getDepartmentAllListData() { // 获取所有数据
      try {
        await this.$store.dispatch('department/GetDepartmentList', {
          request: true,
          showChargedOnly: true
        })
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        })
      }
    },
    async getListData() { // 获取列表数据
      try {
        const { id, type, searchKey } = this
        this.listLoading = true
        let response
        if (type === '1') { // 新增获取员工列表接口
          response = await getEmployeeListCreateAPI({
            ...searchKey,
            ...{
              salaryType: 11
            }
          })
        } else { // 修改、查看获取员工列表接口
          response = await getEmployeeListUpdateAPI({
            id: id
          })
        }
        const result = response
        if (+result.code === 200) {
          if (type === '1') { // 新增
            const resultData = result.data.hrSalaryMonths || []
            this.listData = resultData.map((item) => {
              item.baseSalary = item.salaryBase
              item.assessmentSalary = item.salaryAssessment
              item.postSalary = item.salaryPost
              item.allowanceSalary = item.salaryAllowance
              return item
            })

            // 新增的时候自动生产一个标题
            const year = this.paramsData.salaryDate.substring(0, 4)
            const month = this.paramsData.salaryDate.substring(5, 7)

            this.paramsData.title = `${year}年${month}月-${result.data.deptName}-`
            if (this.paramsData.salaryType == 10) {
              this.paramsData.title += '月薪发放'
            } else if (this.paramsData.salaryType == 20) {
              this.paramsData.title += '工资补发'
            } else if (this.paramsData.salaryType == 11) {
              this.paramsData.title += '月薪发放'
            }
          } else { // 修改和查看
            this.listData = result.data.hrSalaryMonths || []
            this.searchKey.deptId = result.data.deptId
            this.searchKey.salaryDate = formatDate(result.data.salaryMonth, 'yyyy-MM-dd')
          }
          this.totalCount = result.data.hrSalaryMonths.length
          this.pnum = this.totalCount

          // 如果接口返回了pnum，则以接口返回的为准
          if (result.data.pnum) {
            console.log('如果接口返回了pnum，则以接口返回的为准')
            this.pnum = result.data.pnum
          }

          this.deptName = result.data.deptName // 不管新增还是修改，都要传递部门名称

          // alert( this.paramsData.title);
          if (this.paramsData.type === 3) {
            // console.log('修改返回')
            // console.log(this.listData[0])
            this.paramsData.title = result.data.title
            this.paramsData.salaryType = result.data.salaryType

            //  	console.log(this.paramsData);
          }
        } else if (+result.code === 500) {
          this.$router.go(-1)
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '获取列表失败!'
        })
      } finally {
        this.listLoading = false
      }
    },
    async initUpload() { // 初始化上传
      if (this.importInstance) this.importInstance.destroy()
      this.$nextTick(() => {
        // 导入初始化
        if (this.id || true) {
          this.initPlupload({
            container: 'import-box',
            selectFiles: 'upload-import',
            params: {
              submissionId: this.id
            }
          }).then((instance) => {
            this.importInstance = instance
            this.importInstance.init()
            this.importInstance.bind('handleAddFile', (up, result) => {
              up.splice(0, 1)

              this.$confirm('文档已经解析成功，是否确认导入数据?注意：导入后列表已有数据将被清空！！', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async() => {
                // 清空原有数据
                this.listData = result.data || []
                this.totalCount = result.data.length
                this.pnum = this.totalCount
              }).catch(() => {
              })
            })
          }).catch((error) => {
            this.$notify.error({
              title: '错误',
              message: error.message
            })
          })
        }
      })
    },
    async initBeforeRoute(obj, to, from) { // 初始化页面
      this.initUpload() // 初始化导入
      const { id, type = '1', deptId, salaryDate, title, salaryType } = to.query
      obj.type = type
      obj.id = id
      obj.searchKey.deptId = deptId
      obj.searchKey.salaryDate = salaryDate
      obj.paramsData = to.query
      // console.log(to.query)
      if (type === '1') { // 新增
        // alert( obj.paramsData.title);
        if (deptId && salaryDate) {
          obj.isShowSelectParams = false
          obj.getListData()
        } else {
          obj.isShowSelectParams = true
        }
        obj.getDepartmentAllListData()
      } else { // 修改、查看
        if (id) {
          obj.isShowSelectParams = false
          obj.getListData()

          /* if (type === '2') { // 只有修改才有导入
              this.initUpload()
            }*/
        } else {
          this.$router.go(-1)
        }
      }
    },
    async initData() { // 初始化数据
      this.getListData()
      this.getDepartmentAllListData()
    }
  },
  beforeRouteEnter(to, from, next) {
    // console.log(to)
    // console.log(from)
    next(vm => {
      vm.initBeforeRoute(vm, to, from)
    })
  },
  beforeRouteUpdate(to, from, next) {
    // console.log(to)
    // console.log(from)
    this.initBeforeRoute(this, to, from)
    next()
  }
}
</script>

<style lang="scss" scoped>
</style>
